/**
 * Created by maxiaoqiang on 2018/3/23.
 */

// 本地存储封装，项目中其他地方不要直接使用localStorage和sessionStorage，统一使用封装。
const SALT = '__c_fun_admin_';

// 历史路径
import createHistory from 'history/createHashHistory';
const history = createHistory();

// 本地存储
const local = {
    get: (key)=> {
        let strValue = localStorage.getItem(SALT + key);
        return JSON.parse(strValue);
    },
    set: (key, jsonValue)=> {
        var strValue = JSON.stringify(jsonValue);
        localStorage.setItem(SALT + key, strValue);
    },
    remove: (key)=> {
        localStorage.removeItem(SALT + key);
    },
    removeAll: ()=> {
        localStorage.clear();
    }
};

// session存储
const session = {
    get: (key)=> {
        let strValue = sessionStorage.getItem(SALT + key);
        return JSON.parse(strValue)
    },
    set: (key, jsonValue)=> {
        var strValue = JSON.stringify(jsonValue);
        sessionStorage.setItem(SALT + key, strValue);
    },
    remove: (key)=> {
        sessionStorage.removeItem(SALT + key);
    },
    removeAll: ()=> {
        sessionStorage.clear();
    }
};

// 时间格式化多久时间之前
const longAgoFormat = function (timeStr) {
    var date = new Date(timeStr);
    var time = new Date().getTime() - date.getTime(); //现在的时间-传入的时间 = 相差的时间（单位 = 毫秒）
    if (time < 0) {
        return '';
    } else if (time / 1000 < 60) {
        return '刚刚';
    } else if ((time / 60000) < 60) {
        return parseInt((time / 60000)) + '分钟前';
    } else if ((time / 3600000) < 24) {
        return parseInt(time / 3600000) + '小时前';
    } else if ((time / 86400000) < 31) {
        return parseInt(time / 86400000) + '天前';
    } else if ((time / 2592000000) < 12) {
        return parseInt(time / 2592000000) + '月前';
    } else {
        return parseInt(time / 31536000000) + '年前';
    }
};

const windowClient = {
    getClientHeight: ()=> {
        let winHeight;
        if (window.innerHeight) {
            winHeight = window.innerHeight;
        } else if ((document.body) && (document.body.clientHeight)) {
            winHeight = document.body.clientHeight;
        } else if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
            winHeight = document.documentElement.clientHeight;
        }
        return winHeight;
    },
    getClientWidth: ()=> {
        let winWidth;
        if (window.innerWidth) {
            winWidth = window.innerWidth;
        } else if ((document.body) && (document.body.clientWidth)) {
            winWidth = document.body.clientWidth;
        } else if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientWidth) {
            winWidth = document.documentElement.clientWidth;
        }
        return winWidth;
    }
};

// 金额格式化
const formatMoney = function (money, float) {

    if (float == 0) {
        var b = parseInt(money).toString();
        var len = b.length;
        if (len <= 3) {
            return b;
        }
        var r = len % 3;
        return r > 0 ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",") : b.slice(r, len).match(/\d{3}/g).join(",");
    } else {
        float = float > 0 && float <= 20 ? float : 2;
        money = parseFloat((money + "").replace(/[^\d\.-]/g, "")).toFixed(float) + "";

        var l = money.split(".")[0].split("").reverse(),
            n = money.split(".")[1],
            t = "";
        for (var i = 0; i < l.length; i++) {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
        }
        return t.split("").reverse().join("") + "." + n;
    }

};

// 隐藏手机中间四位
const hideAddress = function (telephone) {
    if (telephone.length >= 7) {
        return telephone.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
    } else if (telephone.length >= 2 && telephone.length < 7) {
        return telephone.replace(/(\d)\d*(\d)/, '$1****$2');
    } else {
        return telephone.replace(/(\d)\d*/, '$1****');
    }
};

const formatCount = function (number) {
    number = number.toString();
    if (number.length <= 3) {
        return number
    } else if (number.length > 3 && number.length <= 6) {
        return parseInt(number / 1000) + "k"
    } else {
        return parseInt(number / 10000) + "w"
    }
};

const getTimeSpace = function () {
    var now = new Date();
    var hour = now.getHours();
    if (hour >= 0 && hour < 9) {
        return "morning"
    } else if (hour >= 9 && hour < 13) {
        return "am"
    } else if (hour >= 13 && hour < 19) {
        return "pm"
    } else {
        return "night"
    }
};

const isWeiXin = function () {
    var ua = window.navigator.userAgent.toLowerCase();
    //通过正则表达式匹配ua中是否含有MicroMessenger字符串
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
};


const getParam = function (name) {
    var search = document.location.search;
    //alert(search);
    var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
    var matcher = pattern.exec(search);
    var items = null;
    if (null != matcher) {
        try {
            items = decodeURIComponent(decodeURIComponent(matcher[1]));
        } catch (e) {
            try {
                items = decodeURIComponent(matcher[1]);
            } catch (e) {
                items = matcher[1];
            }
        }
    }
    return items;
};


// 阿拉伯数字转成英文字母
const formatChar = function (number) {
    return String.fromCharCode(65 + parseInt(number));
};

export {
    longAgoFormat,
    formatMoney,
    hideAddress,
    formatCount,
    getTimeSpace,
    isWeiXin,
    getParam,
    formatChar,
    local,
    session,
    history,
    windowClient
};